﻿using JTTD.Common.Attribute;
using JTTD.Domain.IService;
using JTTD.Domain.Units;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;

namespace JTTD.Extensions
{
    /// <summary>
    /// 登录授权验证特性
    /// </summary>
    public class AuthorizeTokenFilter : ActionFilterAttribute
    {
        private readonly IUserInfoService _userInfoService;
        private readonly IMemoryCache _memoryCache;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userInfoService"></param>
        /// <param name="memoryCache"></param>
        public AuthorizeTokenFilter(IUserInfoService userInfoService, IMemoryCache memoryCache)
        {
            _userInfoService = userInfoService;
            _memoryCache = memoryCache;
        }

        /// <summary>
        /// 登录授权验证
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            try
            {
                if (context.Filters.Any(x=>x.GetType().Equals(typeof(UnAuthorize))))
                {
                    return;
                }
                var authorization = context.HttpContext.Request.Headers["authorization"];
                if (string.IsNullOrEmpty(authorization) || string.IsNullOrEmpty(authorization.FirstOrDefault()))
                {
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    context.Result = new JsonResult(ApiResultUnit.Error<string>("token不能为空"));
                    return;
                }
                var token = authorization.FirstOrDefault()?.Replace("Bearer ", "");

                var tokenHandler = new JwtSecurityTokenHandler();
                var jwtSecurityToken = tokenHandler.ReadJwtToken(token);
                var claims = jwtSecurityToken.Claims;
                var user = claims.FirstOrDefault(m => m.Type == "sub").Value;
                var type = claims.FirstOrDefault(m => m.Type == "type").Value;
                //判断当前登陆账号是否可以访问api
                var data= context.ActionDescriptor.EndpointMetadata.FirstOrDefault(item=>item.GetType()==typeof(UserRootAttribute));
                if(data!=null)
                {
                    if (!Convert.ToInt32((data as UserRootAttribute).UserType).ToString().Equals(type))
                    {
                        context.Result = new JsonResult(ApiResultUnit.Error<string>("当前登录账号角色暂无调用此功能权限"));
                        return;
                    }
                }
                context.HttpContext.Session.SetInt32(ApiConsts.UserIdKey, int.Parse(user));
                context.HttpContext.Session.SetInt32(ApiConsts.UserType, int.Parse(type));
            }
            catch (Exception ex)
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                context.Result = new JsonResult(ApiResultUnit.Error<string>(ex.Message));
            }
        }
    }
}
